from mtp.lib.base import *
from mtp.lib.plugin import Plugin 


class PermissionatorController(BaseController):
    @needs_perm('permissions', 'view')
    def index(self):
        c.permissions = model.UserPermission.getAll()
        return render('/permissionator/index.html')

    @needs_perm('permissions', 'grant')
    def grant(self):
        user = request.POST.get('username')
        thing = request.POST.get('thing')
        action = request.POST.get('action')
        if not thing or not action:
            return "cant have empty thing or action"
        if user:
            user = model.User.getByUsername(user)
            if not user:
                return "user not found"
        model.UserPermission.grant(user, thing, action)
        redirect_to(h.url_for('permissions'))
    
    @needs_perm('permissions', 'revoke')
    def revoke(self):
        user = request.POST.get('username') or None
        thing = request.POST.get('thing')
        action = request.POST.get('action')
        if not thing or not action:
            return "cant have empty thing or action"
        if user:
            user = model.User.getByUsername(user)
            if not user:
                return "user not found"
        model.UserPermission.revoke(user, thing, action)
        redirect_to(h.url_for('permissions'))
 

class PermissionatorPlugin(Plugin):
    def __init__(self, **options):
        config['mtp.controllers']['permissions'] = PermissionatorController
        map = config['routes.map']

        map.connect('permissions', 'permissions', 
                    controller='permissions', action='index')
        map.connect('permissions/grant', controller='permissions', action='grant')
        map.connect('permissions/revoke', controller='permissions', action='revoke')

        config['mtp.permissions']['permissions'].update(('view', 'grant', 'revoke'))









